"use client"

import { useState, useEffect } from 'react'

interface ShootingGameProps {
  targetChar: string
  onGameEnd: (score: number, correct: number, total: number) => void
}

interface Bullet {
  id: number
  content: string
  isShot: boolean
}

export function ShootingGame({ targetChar, onGameEnd }: ShootingGameProps) {
  const [targetCharacter, setTargetCharacter] = useState('地')
  const [requiredComponents, setRequiredComponents] = useState<string[]>(['土', '也'])
  const [availableBullets, setAvailableBullets] = useState<Bullet[]>([])
  const [shotComponents, setShotComponents] = useState<string[]>([])
  const [score, setScore] = useState(0)
  const [timeLeft, setTimeLeft] = useState(60)
  const [level, setLevel] = useState(1)
  const [gameStarted, setGameStarted] = useState(false)
  const [isCompleted, setIsCompleted] = useState(false)

  // 初始化游戏
  useEffect(() => {
    initializeGame()
  }, [])

  // 计时器
  useEffect(() => {
    if (gameStarted && timeLeft > 0 && !isCompleted) {
      const timer = setTimeout(() => {
        setTimeLeft(prev => prev - 1)
      }, 1000)
      return () => clearTimeout(timer)
    } else if (timeLeft === 0) {
      onGameEnd(score, shotComponents.length, requiredComponents.length)
    }
  }, [timeLeft, gameStarted, score, shotComponents.length, requiredComponents.length, isCompleted, onGameEnd])

  const initializeGame = () => {
    // 字根组合数据
    const puzzles = [
      { target: '地', components: ['土', '也'] },
      { target: '河', components: ['氵', '可'] },
      { target: '村', components: ['木', '寸'] },
      { target: '池', components: ['氵', '也'] },
      { target: '城', components: ['土', '成'] }
    ]

    const currentPuzzle = puzzles.find(p => p.target === targetChar) || puzzles[0]
    setTargetCharacter(currentPuzzle.target)
    setRequiredComponents(currentPuzzle.components)

    // 创建子弹（包含正确和干扰项）
    const correctBullets = currentPuzzle.components
    const distractorBullets = ['支', '皮', '火', '水', '木', '人']
    const allBullets = [...correctBullets, ...distractorBullets.slice(0, 2)]
    
    const bullets: Bullet[] = allBullets.map((content, index) => ({
      id: index,
      content,
      isShot: false
    }))

    // 打乱顺序
    const shuffledBullets = bullets.sort(() => Math.random() - 0.5)
    setAvailableBullets(shuffledBullets)
    setShotComponents([])
    setIsCompleted(false)
  }

  const handleBulletShoot = (bullet: Bullet) => {
    if (!gameStarted) setGameStarted(true)
    if (bullet.isShot) return

    // 标记子弹为已射击
    const newBullets = availableBullets.map(b => 
      b.id === bullet.id ? { ...b, isShot: true } : b
    )
    setAvailableBullets(newBullets)

    // 检查是否是正确的组件
    if (requiredComponents.includes(bullet.content)) {
      const newShotComponents = [...shotComponents, bullet.content]
      setShotComponents(newShotComponents)
      setScore(prev => prev + 50)

      // 检查是否完成
      if (newShotComponents.length === requiredComponents.length) {
        setIsCompleted(true)
        setScore(prev => prev + 100) // 完成奖励
        setTimeout(() => {
          onGameEnd(score + 150, newShotComponents.length, requiredComponents.length)
        }, 2000)
      }
    } else {
      // 射击错误，扣分
      setScore(prev => Math.max(0, prev - 25))
    }
  }

  const resetGame = () => {
    setScore(0)
    setTimeLeft(60)
    setGameStarted(false)
    initializeGame()
  }

  return (
    <div className="h-full flex flex-col bg-white rounded-2xl p-6 relative">
      {/* 游戏标题和关闭按钮 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-orange-500 rounded-lg flex items-center justify-center">
            <span className="text-white text-lg">🎯</span>
          </div>
          <h3 className="text-xl font-bold text-gray-800">字根射击</h3>
        </div>
        <button
          onClick={() => onGameEnd(score, shotComponents.length, requiredComponents.length)}
          className="w-8 h-8 bg-red-500 rounded-full flex items-center justify-center text-white hover:bg-red-600 transition-colors"
        >
          ✕
        </button>
      </div>

      {/* 游戏状态栏 */}
      <div className="grid grid-cols-3 gap-4 mb-6">
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{score}</div>
          <div className="text-sm text-gray-600">得分</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">
            {Math.floor(timeLeft / 60).toString().padStart(2, '0')}:
            {(timeLeft % 60).toString().padStart(2, '0')}
          </div>
          <div className="text-sm text-gray-600">时间</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{level}</div>
          <div className="text-sm text-gray-600">关卡</div>
        </div>
      </div>
      
      {/* 游戏区域 */}
      <div className="flex-1 flex flex-col items-center justify-center space-y-8">
        {/* 游戏说明和目标 */}
        <div className="text-center">
          <div className="text-lg font-bold text-gray-700 mb-2">🎯 字根射击</div>
          <div className="text-sm text-gray-600 mb-4">射击正确的字根组成目标汉字</div>
          
          <div className="text-center">
            <div className="text-lg font-bold text-gray-700 mb-2">目标：</div>
            <div className="text-6xl font-bold text-gray-800 mb-4">{targetCharacter}</div>
          </div>
        </div>

        {/* 射击目标区域 */}
        <div className="flex items-center justify-center space-x-6">
          {requiredComponents.map((component, index) => (
            <div
              key={index}
              className={`
                w-20 h-20 rounded-full border-2 flex items-center justify-center
                transition-all duration-300
                ${shotComponents.includes(component)
                  ? 'bg-green-100 border-green-400 text-green-700'
                  : 'bg-blue-100 border-blue-400 text-blue-700'
                }
              `}
            >
              <span className="text-2xl font-bold">
                {shotComponents.includes(component) ? component : '?'}
              </span>
            </div>
          ))}
        </div>

        {/* 已射击提示 */}
        <div className="text-center">
          <div className="text-sm text-gray-600">已射击：</div>
          <div className="flex justify-center space-x-2 mt-2">
            {shotComponents.map((component, index) => (
              <span
                key={index}
                className="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm font-bold"
              >
                {component}
              </span>
            ))}
          </div>
        </div>

        {/* 子弹区域 */}
        <div className="flex flex-wrap justify-center gap-4">
          {availableBullets.map((bullet) => (
            <div
              key={bullet.id}
              onClick={() => handleBulletShoot(bullet)}
              className={`
                w-16 h-16 rounded-full flex items-center justify-center cursor-pointer
                transition-all duration-300 transform hover:scale-110 shadow-lg
                ${bullet.isShot
                  ? 'bg-gray-300 text-gray-500 cursor-not-allowed opacity-50'
                  : requiredComponents.includes(bullet.content)
                  ? 'bg-gradient-to-br from-blue-400 to-blue-500 hover:from-blue-500 hover:to-blue-600 text-white'
                  : 'bg-gradient-to-br from-red-400 to-red-500 hover:from-red-500 hover:to-red-600 text-white'
                }
              `}
            >
              <span className="text-lg font-bold">
                {bullet.isShot ? '✓' : bullet.content}
              </span>
            </div>
          ))}
        </div>

        {/* 完成提示 */}
        {isCompleted && (
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600 mb-2">🎉 射击完成！</div>
            <div className="text-lg text-gray-600">恭喜你成功射击组成了"{targetCharacter}"字！</div>
          </div>
        )}
      </div>

      {/* 底部控制按钮 */}
      <div className="flex justify-center space-x-4 mt-6">
        <button 
          onClick={() => setGameStarted(!gameStarted)}
          className="px-6 py-2 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors flex items-center space-x-2"
        >
          <span>{gameStarted ? '⏸️' : '▶️'}</span>
          <span>{gameStarted ? '暂停' : '开始'}</span>
        </button>
        <button 
          onClick={resetGame}
          className="px-6 py-2 bg-orange-500 text-white rounded-full hover:bg-orange-600 transition-colors flex items-center space-x-2"
        >
          <span>🔄</span>
          <span>重新开始</span>
        </button>
        <button className="px-6 py-2 bg-green-500 text-white rounded-full hover:bg-green-600 transition-colors flex items-center space-x-2">
          <span>⏭️</span>
          <span>下一关</span>
        </button>
        <button 
          onClick={() => onGameEnd(score, shotComponents.length, requiredComponents.length)}
          className="px-6 py-2 bg-gray-500 text-white rounded-full hover:bg-gray-600 transition-colors flex items-center space-x-2"
        >
          <span>🚪</span>
          <span>退出游戏</span>
        </button>
      </div>
    </div>
  )
} 